import { useEffect, useState, useImperativeHandle, forwardRef } from 'react'
import { Button, Pagination, Drawer, Input, Form, InputNumber, message } from 'antd'
import styles from './index.module.css'
import { getImageClass, addImgClass, delImageClass, editImageClass } from '@/api/image'
import { CloseOutlined, EditOutlined } from '@ant-design/icons'

interface ClassType {
  id: number
  images_count: number
  name: string
  order: number
}
function image(props: any, ref: React.Ref<any>) {
  useImperativeHandle(ref, () => {
    return { showDrawer }
  })
  const [form] = Form.useForm()
  const [imgClassList, setImgClass] = useState<ClassType[]>([])
  const [selectClass, setSelectClass] = useState(168)
  const [classPage, setClassPage] = useState(1)
  const [total, setTotal] = useState(0)
  useEffect(() => {
    getImgClassList()
  }, [])
  const getImgClassList = () => {
    getImageClass(classPage).then(res => {
      if (res.status === 200) {
        setImgClass(res.data.list)
        setSelectClass(res.data.list[0].id)
        props.setClassPage(res.data.list[0].id)
        setTotal(res.data.totalCount)
      }
    })
  }
  const classClick = (id: number) => {
    setSelectClass(id)
    props.setClassPage(id)
  }

  useEffect(() => {
    getImgClassList()
  }, [classPage])

  const onClassChange = (e: number) => {
    setClassPage(e)
  }

  // 添加分类弹出框
  const [open, setOpen] = useState(false)
  const onClose = () => {
    setOpen(false)
  }
  const showDrawer = () => {
    setOpen(true)
  }
  // 删除分类
  const delImgClass = (id: number) => {
    delImageClass(id).then(res => {
      if (res.status === 200) {
        message.success('删除成功')
        if (classPage !== 1) {
          setClassPage(1)
        } else {
          getImgClassList()
        }
      }
    })
  }
  // 添加分类
  const saveAddClass = () => {
    form
      .validateFields()
      .then(values => {
        if (editId !== 0) {
          console.log(editId)
          editImageClass(editId, values).then(res => {
            if (res.status === 200) {
              if (classPage !== 1) {
                setClassPage(1)
              } else {
                getImgClassList()
              }
              onClose()
              setEditId(0)
              message.success('修改成功')
              form.resetFields()
            }
          })
          return
        }
        addImgClass(values).then(res => {
          if (res.status === 200) {
            if (classPage !== 1) {
              setClassPage(1)
            } else {
              getImgClassList()
            }
            onClose()
            form.resetFields()
            message.success('添加成功')
          }
        })
      })
      .catch(err => {
        console.log(err)
      })
  }
  const initialValues = {
    name: '',
    order: 50
  }
  const [editId, setEditId] = useState(0)

  // 编辑分类
  const ediImgClass = (item: ClassType) => {
    console.log(item)
    setEditId(item.id)
    // form表单的值不能被state监听
    form.setFieldsValue({
      name: item.name,
      order: item.order
    })
    showDrawer()
  }
  const btn = (
    <div>
      <Button type='primary' size='large' onClick={saveAddClass}>
        提交
      </Button>
      <Button size='large' style={{ marginLeft: '15px' }} onClick={onClose}>
        取消
      </Button>
    </div>
  )
  return (
    <>
      <div className={styles.image}>
        {imgClassList.map(item => {
          return (
            <div
              className={selectClass === item.id ? `${styles.imgClassItem} ${styles.active}` : styles.imgClassItem}
              key={item.id}
              onClick={() => classClick(item.id)}
            >
              {item.name}
              <div style={{ color: '#6cb4ff' }}>
                <EditOutlined onClick={() => ediImgClass(item)} style={{ marginRight: '10px' }} />
                <CloseOutlined
                  onClick={() => {
                    delImgClass(item.id)
                  }}
                />
              </div>
            </div>
          )
        })}
        <Pagination simple={{ readOnly: true }} showSizeChanger={false} defaultCurrent={classPage} total={total} onChange={onClassChange} />
        <Drawer title='新增图片分类' footer={btn} onClose={onClose} open={open} width={'30%'}>
          相册名称:
          <Form form={form} initialValues={initialValues} name='control-hooks' style={{ maxWidth: 600 }}>
            <Form.Item name='name' label='图片分类名称' rules={[{ required: true, message: '请输入图片分类名称' }]}>
              <Input value={initialValues.name} />
            </Form.Item>
            <Form.Item name='order' label='排序'>
              <InputNumber min={1} max={9999} value={initialValues.order} />
            </Form.Item>
          </Form>
        </Drawer>
      </div>
    </>
  )
}
export default forwardRef(image)
